package cm.mefobe.android.telecomcost.activities;

import java.util.ArrayList;
import cm.mefobe.android.telecomcost.R;
import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.adapter.VoiceRateAdapter;
import cm.mefobe.android.telecomcost.entities.Country;
import cm.mefobe.android.telecomcost.entities.Destination;
import cm.mefobe.android.telecomcost.entities.Provider;
import cm.mefobe.android.telecomcost.entities.VoiceRate;
import cm.mefobe.android.telecomcost.entities.Zone;
import cm.mefobe.android.telecomcost.view.PickerView;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class NumberInfoActivity extends TelecomcostActivity {

	private ListView list;

	private ArrayList<Zone> _zones;
	private PickerView numberView;
	private TextView lblDestination;

	/*
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("NumberInfoActivity", "Creating the activity");

		super.onCreate(savedInstanceState);

		setContentView(R.layout.phone_number_info);

		numberView = (PickerView) findViewById(R.id.pickerView1);
		lblDestination = (TextView) findViewById(R.id.lblDestination);
		list = (ListView) findViewById(R.id.listViewVoiceRates);

		numberView.getEditText().setInputType(InputType.TYPE_CLASS_PHONE);
		numberView.getButton().setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				showNumberInfos(numberView.getText());
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				showSelectedVoiceRate(arg2);
			}
		});
	}

	protected void showNumberInfos(String number) {
		Log.i("NumberInfoActivity", "showing infos for number..." + number);
		Destination dest = null;

		if (_zones != null) {
			int index = 0;

			while (index < _zones.size()) {
				Zone zone = _zones.get(index);
				ArrayList<Country> zoneCountries = zone.getCountries();

				int j = 0;

				while (j < zoneCountries.size()) {
					Country country = zoneCountries.get(j);
					if (number.startsWith(country.getCode())
							|| number.startsWith("+" + country.getCode())
							|| number.startsWith("00" + country.getCode())) {
						Log.i("NumberInfoActivity",
								"country " + country.getName()
										+ " found in zone " + zone.getName());
						dest = new Destination();
						dest.setZone(zone);
						dest.setCountry(country);

						if (number.startsWith(country.getCode())) {
							number = number.substring(country.getCode()
									.length());
						}
						if (number.startsWith("+" + country.getCode())) {
							number = number.substring(("+" + country.getCode())
									.length());
						}
						if (number.startsWith("00" + country.getCode())) {
							number = number
									.substring(("00" + country.getCode())
											.length());
						}

						Log.i("NumberInfoActivity",
								"we look for the provider in the rest of the number..."
										+ number);

						int k = 0;

						ArrayList<Provider> providers = country.getProviders();

						while (k < providers.size()) {
							Provider provider = providers.get(k);
							String[] prefixes = provider.getPrefixes().split(
									";");

							int n = 0;

							while (n < prefixes.length) {
								if (number.startsWith(prefixes[n])) {
									Log.i("NumberInfoActivity",
											"we have our provider..."
													+ provider.getName());
									dest.setProvider(provider);
								}

								n++;
							}

							k++;
						}
					}
					j++;
				}

				index++;
			}

			lblDestination.setText(dest != null ? dest.toString()
					: "unknown destination");
			filterVoiceRates(dest);
		} else {
			throw new UnsupportedOperationException(
					"cannot parse this number...zones not loaded");
		}
	}

	private void filterVoiceRates(Destination dest) {
		Log.i("VoiceRateListActivity", "binding voice rates for this number");

		if (dest != null) {
			ArrayList<VoiceRate> _voiceRates = TelecomCost.getDatabaseManager()
					.getVoiceRates();
			ArrayList<VoiceRate> filteredVoiceRates = new ArrayList<VoiceRate>();

			int index = 0;

			while (index < _voiceRates.size()) {
				if (_voiceRates.get(index).getDestinationLabel()
						.equals(dest.toString())) {
					Log.i("DestinationPickerView", dest.toString() + " = "
							+ _voiceRates.get(index).getDestinationLabel());
					filteredVoiceRates.add(_voiceRates.get(index));
				}
				index++;
			}

			list.setAdapter(new VoiceRateAdapter(NumberInfoActivity.this,
					R.layout.item_row, filteredVoiceRates));
		} else {
			list.setAdapter(new VoiceRateAdapter(NumberInfoActivity.this,
					R.layout.item_row, new ArrayList<VoiceRate>()));
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		Log.i("NumberInfoActivity", "creating options menu for VoiceRates : ");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.standard_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_item_new:
			return true;
		case R.id.menu_item_delete:
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected void showSelectedVoiceRate(int index) {

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		Log.i("NumberInfoActivity", "Destroying the activity ");
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();

		Log.i("NumberInfoActivity", "Pausing the activity ");
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		Log.i("NumberInfoActivity", "Postcreating the activity ");
	}

	@Override
	protected void onPostResume() {
		super.onPostResume();
		Log.i("NumberInfoActivity", "PostResuming the activity");
		bindZones();
	}

	private void bindZones() {
		Log.i("NumberInfoActivity", "binding zones");
		_zones = TelecomCost.getDatabaseManager().getZones();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
		Log.i("NumberInfoActivity", "Restarting the activity ");
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		Log.i("NumberInfoActivity", "onRestoreInstanceState the activity ");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i("NumberInfoActivity", "Resuming the activity");
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		Log.i("NumberInfoActivity", "onSaveInstanceState the activity");
	}

	@Override
	protected void onStart() {
		super.onStart();
		Log.i("NumberInfoActivity", "Starting the activity ");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.i("NumberInfoActivity", "Stopping the activity");
	}
}
